package org.xiezc.util;

/**
 * 组装微信消息的类
 * 
 * @author xiezc
 *
 */
public class MessageBuilder {

	private StringBuilder builder;

	public MessageBuilder() {
		builder = new StringBuilder();
	}

	public MessageBuilder(int capacity) {
		builder = new StringBuilder(capacity);
	}

	public MessageBuilder(String str) {
		builder = new StringBuilder(str);
	}

	public void append(String str) {
		builder.append(str);
	}

	public void insert(String str) {
		builder.insert(0, str);
	}

	/**
	 * 使用${tag}标签对已有的消息进行包含
	 * 
	 * @param tag
	 */
	public void surroundWith(String tag) {
		StringBuilder sb = new StringBuilder(builder.capacity() + tag.length() * 2 + 5);
		sb.append("<").append(tag).append(">\n").append(builder).append("</").append(tag).append(">\n");
		builder = sb;
	}

	/**
	 * 增加一个标签和内容 ，里面的内容也会被xml解析器解析
	 * 
	 * @param tagName
	 * @param text
	 */
	public void addTag(String tagName, String text) {
		if (text == null) {
			return;
		}
		builder.append("<").append(tagName).append(">").append(text).append("</").append(tagName).append(">\n");
	}

	/**
	 * 增加一个标签和内容 ,标签中的内容被‘<![CDATA[’和‘]]>’包围 ，因此不会被解析，
	 * 
	 * @param tagName
	 * @param data
	 */
	public void addData(String tagName, String data) {
		if (data == null) {
			return;
		}
		builder.append("<").append(tagName).append("><![CDATA[").append(data).append("]]></").append(tagName)
				.append(">\n");
	}

	@Override
	public String toString() {
		return builder.toString();
	}

}
